package com.tadpole.music.view.activity.me.yun;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.czt.mp3recorder.MP3Recorder;
import com.shuyu.waveview.AudioPlayer;
import com.shuyu.waveview.FileUtils;
import com.tadpole.music.R;
import com.tadpole.music.bean.me.yun.YunQuestionBean;
import com.tadpole.music.bean.me.yun.YunSubjectBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.me.yun.YunSubjectIView;
import com.tadpole.music.iView.me.yun.YunSubmitIView;
import com.tadpole.music.presenter.me.yun.YunSubjectPresenter;
import com.tadpole.music.presenter.me.yun.YunSubmitPresenter;
import com.tadpole.music.utils.JsonParseUtil;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.QiniuYunUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.single.YunQuestionSingle;
import com.tadpole.music.view.widget.LollipopFixedWebView;
import com.tadpole.music.view.widget.YunOutPopup;
import com.white.progressview.HorizontalProgressView;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 蝌蚪云考试  选择题
 * Created By 孙岩
 * on 2021/2/9
 */
public class YunExaminationTwoActivity extends BaseActivity implements YunSubjectIView , YunSubmitIView {
    //回退
    private View view_back_icon;
    //标题
    private TextView actionbar_title;
    //倒计时
    private TextView tvTime;
    //第几题
    private TextView tvCount;
    //录音中
    private LinearLayout llLuYin;
    //题目
    private LollipopFixedWebView tvTitle;
    //图片
    private ImageView ivImage;
    //ABCD 选项
    private LinearLayout llSelect;
    //开始录音
    private TextView tvRadio;
    //播放录音
    private TextView tvPlayRadio;
    //提交
    private TextView tvSubmit;
    //web
    private WebSettings webSettings;
    private LinearLayout llA;
    private LinearLayout llB;
    private LinearLayout llC;
    private LinearLayout llD;
    private TextView tvA;
    private TextView tvB;
    private TextView tvC;
    private TextView tvD;
    private ImageView ivA;
    private ImageView ivB;
    private ImageView ivC;
    private ImageView ivD;
    private TextView tvAText;
    private TextView tvBText;
    private TextView tvCText;
    private TextView tvDText;

    //标题
    private String title;
    //数据源
    private YunSubjectBean.DataBeanX bean;
    //获取题
    private YunSubjectPresenter yunSubjectPresenter;

    //当前播放到的position
    private int position = 0;
    //正确答案
    private int right_answer;

    //    //第一次进来播放的12345
    private static MediaPlayer media1;
    //播放text的
    private static AudioPlayer audioText;
    //有音频的选择题 播放12345
    private static MediaPlayer media2;
    //有音频 播放音频的
    private static AudioPlayer player;

    //录音路径
    private String filePath = "";
    //上传七牛录音路径
    private String qnPath = "";
    //生成mp3的recorder
    private MP3Recorder mRecorder;
    //录音以后的播放控件
    private AudioPlayer audioPlayer;

    //判断是否正在播放
    private boolean isPlay = false;
    //false 标识正在上传 true 标识上传完成
    private boolean isqnPath = false;
    //每道小题的倒计时
    private Time timeQuestion;
    private Time1 time1Question;
    //是否正在录音
    private boolean isAudio = false;
    //
    private HorizontalProgressView progress1;
    //提交考试
    private YunSubmitPresenter yunSubmitPresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yun_examination_two);
        timeQuestion = new Time(20000, 1000);
        time1Question = new Time1(60000, 1000);
        title = getIntent().getStringExtra("title");

        initViews();
        initListeners();

        yunSubjectPresenter = new YunSubjectPresenter();
        yunSubjectPresenter.attachView(this);
        yunSubjectPresenter.getYunSubject();

        yunSubmitPresenter = new YunSubmitPresenter();
        yunSubmitPresenter.attachView(this);
    }

    //初始化控件
    private void initViews() {
        view_back_icon = findViewById(R.id.view_back_icon);
        actionbar_title = findViewById(R.id.actionbar_title);
        tvTime = findViewById(R.id.tvTime);
        tvCount = findViewById(R.id.tvCount);
        llLuYin = findViewById(R.id.llLuYin);
        tvTitle = findViewById(R.id.tvTitle);
        ivImage = findViewById(R.id.ivImage);
        llSelect = findViewById(R.id.llSelect);
        tvRadio = findViewById(R.id.tvRadio);
        tvPlayRadio = findViewById(R.id.tvPlayRadio);
        llA = findViewById(R.id.llA);
        llB = findViewById(R.id.llB);
        llC = findViewById(R.id.llC);
        llD = findViewById(R.id.llD);
        tvA = findViewById(R.id.tvA);
        tvB = findViewById(R.id.tvB);
        tvC = findViewById(R.id.tvC);
        tvD = findViewById(R.id.tvD);
        ivA = findViewById(R.id.ivA);
        ivB = findViewById(R.id.ivB);
        ivC = findViewById(R.id.ivC);
        ivD = findViewById(R.id.ivD);
        tvAText = findViewById(R.id.tvAText);
        tvBText = findViewById(R.id.tvBText);
        tvCText = findViewById(R.id.tvCText);
        tvDText = findViewById(R.id.tvDText);
        tvSubmit = findViewById(R.id.tvSubmit);
        progress1 = findViewById(R.id.progress1);

        actionbar_title.setText(title);

        webSettings = tvTitle.getSettings();
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);
        //webView 为透明
        tvTitle.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true);//允许使用js
        //webView 为透明
        tvTitle.setBackgroundColor(0);
        progress1.setProgress(0);
    }

    //初始化监听器
    private void initListeners() {
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                YunExaminationTwoActivity.this.finish();
            }
        });

        llA.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    //倒计时结束
                    timeQuestion.cancel();
                    tvTime.setText("倒计时：20s");
                    YunQuestionBean dataBean = new YunQuestionBean();
                    dataBean.setId(bean.getData().get(position).getId());
                    dataBean.setAnswer("1");
                    if (bean.getData().get(position).getRight_answer() == 1) {
                        dataBean.setResult(true);
                    } else {
                        dataBean.setResult(false);
                    }
                    YunQuestionSingle.getInstance().addWorks(dataBean);
                    stopPlay();
                    next();

                } else {
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });

        llB.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    //倒计时结束
                    timeQuestion.cancel();
                    tvTime.setText("倒计时：20s");
                    YunQuestionBean dataBean = new YunQuestionBean();
                    dataBean.setId(bean.getData().get(position).getId());
                    dataBean.setAnswer("2");
                    if (bean.getData().get(position).getRight_answer() == 2) {
                        dataBean.setResult(true);
                    } else {
                        dataBean.setResult(false);
                    }
                    YunQuestionSingle.getInstance().addWorks(dataBean);
                    stopPlay();
                    next();
                } else {
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });

        llC.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    //倒计时结束
                    timeQuestion.cancel();
                    tvTime.setText("倒计时：20s");
                    YunQuestionBean dataBean = new YunQuestionBean();
                    dataBean.setId(bean.getData().get(position).getId());
                    dataBean.setAnswer("3");
                    if (bean.getData().get(position).getRight_answer() == 3) {
                        dataBean.setResult(true);
                    } else {
                        dataBean.setResult(false);
                    }
                    YunQuestionSingle.getInstance().addWorks(dataBean);
                    stopPlay();
                    next();

                } else {
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });

        llD.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    //倒计时结束
                    timeQuestion.cancel();
                    tvTime.setText("倒计时：20s");
                    YunQuestionBean dataBean = new YunQuestionBean();
                    dataBean.setId(bean.getData().get(position).getId());
                    dataBean.setAnswer("4");
                    if (bean.getData().get(position).getRight_answer() == 4) {
                        dataBean.setResult(true);
                    } else {
                        dataBean.setResult(false);
                    }
                    YunQuestionSingle.getInstance().addWorks(dataBean);
                    stopPlay();
                    next();

                } else {
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });

        //录音
        tvRadio.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (isPlay) {
                    if (tvRadio.getText().toString().trim().equals("开始录音")) {
                        startRecord();
                        tvRadio.setText("停止录音");
                        llLuYin.setVisibility(View.VISIBLE);
                        llLuYin.bringToFront();
                        tvPlayRadio.setVisibility(View.VISIBLE);
                        isAudio = true;
                    } else if (tvRadio.getText().toString().trim().equals("停止录音")) {
                        stopRecord();
                        tvRadio.setText("录音结束");
                        tvRadio.setEnabled(false);
                        llLuYin.setVisibility(View.GONE);
                        uploadAvatar();
                        isAudio = false;
                    }
                } else {
                    ToastUtils.show("请等待标准音播放结束");
                }
            }
        });

        //播放录音
        tvPlayRadio.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (filePath.equals("")) {
                    ToastUtils.show("请先进行录制");
                } else if (tvRadio.getText().toString().trim().equals("停止录音")) {
                    ToastUtils.show("请先点击停止录音");
                } else {
                    playInModeStream();
                }
            }
        });

        tvSubmit.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (filePath.equals("")) {
                        ToastUtils.show("请先录音");
                    } else {
                        if (isqnPath) {
                            YunQuestionBean dataBean = new YunQuestionBean();
                            dataBean.setId(bean.getData().get(position - 1).getId());
                            dataBean.setAnswer(qnPath);
                            dataBean.setResult(true);
                            YunQuestionSingle.getInstance().addWorks(dataBean);
                            String question_answers = JsonParseUtil.ListToStr(YunQuestionSingle.getInstance().getWorksList());
                            int score = 0;
                            for(int i=0;i<YunQuestionSingle.getInstance().getWorksList().size();i++){
                                if(YunQuestionSingle.getInstance().getWorksList().get(i).isResult()){
                                    score+=4;
                                }
                            }
                            yunSubmitPresenter.submit(question_answers,score+"",bean.getExam_id()+"","");
                        } else {
                            ToastUtils.show("请等待录音上传完成");
                        }
                    }
                } else {
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });
    }

    /**
     * 播放
     */
    @SuppressLint("HandlerLeak")
    private void playInModeStream() {
        if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
            Toast.makeText(YunExaminationTwoActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        audioPlayer = new AudioPlayer(YunExaminationTwoActivity.this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间

                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束

                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始

                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误

                        break;
                }

            }
        });

        audioPlayer.playUrl(filePath);
    }

    @Override
    public void showSubject(YunSubjectBean.DataBeanX bean) {
        this.bean = bean;
        next();
    }

    //播放 等等 操作
    @SuppressLint("SetTextI18n")
    private void next() {

        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.app_icon)
                .error(R.mipmap.app_icon)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);

        if (bean.getData().get(position).getAnswer_type() == 1 && bean.getData().get(position).getRight_answer() != -1) {//文字

            llSelect.setVisibility(View.VISIBLE);
            tvRadio.setVisibility(View.GONE);
            tvPlayRadio.setVisibility(View.GONE);

            ivA.setVisibility(View.GONE);
            ivB.setVisibility(View.GONE);
            ivC.setVisibility(View.GONE);
            ivD.setVisibility(View.GONE);
            tvAText.setVisibility(View.VISIBLE);
            tvBText.setVisibility(View.VISIBLE);
            tvCText.setVisibility(View.VISIBLE);
            tvDText.setVisibility(View.VISIBLE);

            tvAText.setText(bean.getData().get(position).getAnswer_a());
            tvBText.setText(bean.getData().get(position).getAnswer_b());
            tvCText.setText(bean.getData().get(position).getAnswer_c());
            tvDText.setText(bean.getData().get(position).getAnswer_d());

            if (bean.getData().get(position).getAnswer_c().equals("")) {
                llC.setVisibility(View.GONE);
            } else {
                llC.setVisibility(View.VISIBLE);
            }

            if (bean.getData().get(position).getAnswer_d().equals("")) {
                llD.setVisibility(View.GONE);
            } else {
                llD.setVisibility(View.VISIBLE);
            }

        } else if (bean.getData().get(position).getAnswer_type() == 2 || bean.getData().get(position).getAnswer_type() == 5) {//图片
            llSelect.setVisibility(View.VISIBLE);
            tvRadio.setVisibility(View.GONE);
            tvPlayRadio.setVisibility(View.GONE);

            ivA.setVisibility(View.VISIBLE);
            ivB.setVisibility(View.VISIBLE);
            ivC.setVisibility(View.VISIBLE);
            ivD.setVisibility(View.VISIBLE);
            tvAText.setVisibility(View.GONE);
            tvBText.setVisibility(View.GONE);
            tvCText.setVisibility(View.GONE);
            tvDText.setVisibility(View.GONE);

            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(position).getAnswer_a()).apply(requestOptions).into(ivA);
            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(position).getAnswer_b()).apply(requestOptions).into(ivB);
            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(position).getAnswer_c()).apply(requestOptions).into(ivC);
            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(position).getAnswer_d()).apply(requestOptions).into(ivD);

            if (bean.getData().get(position).getAnswer_c().equals("")) {
                llC.setVisibility(View.GONE);
            } else {
                llC.setVisibility(View.VISIBLE);
            }

            if (bean.getData().get(position).getAnswer_d().equals("")) {
                llD.setVisibility(View.GONE);
            } else {
                llD.setVisibility(View.VISIBLE);
            }

        } else {//视唱
            llSelect.setVisibility(View.GONE);
            tvRadio.setVisibility(View.VISIBLE);
            tvPlayRadio.setVisibility(View.VISIBLE);
        }

        //页数
        tvCount.setText("第" + (position + 1) + "题");

        String url = UrlConfig.getTitle + "q_type=question&id=" + bean.getData().get(position).getId();
        tvTitle.loadUrl(url);

        if (bean.getData().get(position).getTitle_img().equals("")) {
            ivImage.setVisibility(View.GONE);
        } else {
            ivImage.setVisibility(View.VISIBLE);
            Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(position).getTitle_img()).apply(requestOptions).into(ivImage);
        }

        right_answer = bean.getData().get(position).getRight_answer();

        playAuDio(bean.getData().get(position).getTitle_sound(), bean.getData().get(position).getBg_sound(), bean.getData().get(position).getPlay_times() == 3 ? 2 : bean.getData().get(position).getPlay_times());


        position = position + 1;

        if (position == bean.getData().size()) {
            tvSubmit.setVisibility(View.VISIBLE);
            tvTime.setText("倒计时：60s");
        } else {
            tvSubmit.setVisibility(View.GONE);
            tvTime.setText("倒计时：20s");
        }
    }

    /**
     * 播放音频
     *
     * @param title_sound 题目音频
     * @param bg_sound    内容音频
     * @param play_times  内容播放次数
     */
    @SuppressLint("HandlerLeak")
    private void playAuDio(final String title_sound, final String bg_sound, final int play_times) {

        if (media1 != null) {
            media1.stop();
            media1.release();
        }
        //播放本地123456
        media1 = MediaPlayer.create(YunExaminationTwoActivity.this, redia(position));
        media1.start();
        media1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (audioText != null) {
                    audioText.pause();
                    audioText.stop();
                }
                if (title_sound.equals("")) {
                    playCount(bg_sound, play_times, 0);
                } else {
                    audioText = new AudioPlayer(YunExaminationTwoActivity.this, new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            switch (msg.what) {
                                case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                                    break;
                                case AudioPlayer.HANDLER_COMPLETE://text播放结束
                                    playCount(bg_sound, play_times, 0);
                                    break;
                                case AudioPlayer.HANDLER_PREPARED://播放开始
                                    break;
                                case AudioPlayer.HANDLER_ERROR://播放错误
                                    break;
                            }

                        }
                    });
                    audioText.playUrl(Constant.IMAGE_HEAD + title_sound);
                }
            }
        });
    }

    private void playCount(final String bg_sound, final int cycler, final int count) {
        if (bg_sound.equals("")) {
            if(position==bean.getData().size()){
                time1Question.start();
            }else{
                timeQuestion.start();
            }
        } else {
            if (media2 != null) {
                media2.stop();
                media2.release();
            }

            media2 = MediaPlayer.create(YunExaminationTwoActivity.this, rediaCount(count));
            media2.start();

            media2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    playWork(bg_sound, cycler, count + 1);
                }
            });
        }
    }

    //播放网络  count 当前播放到第几遍
    @SuppressLint("HandlerLeak")
    private void playWork(final String urlMusic, final int cycler, final int count) {
        player = new AudioPlayer(YunExaminationTwoActivity.this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束
                        if (cycler == 1) {
                            isPlay = true;
                            if(position==bean.getData().size()){
                                time1Question.start();
                            }else{
                                timeQuestion.start();
                            }
                        } else if (cycler == 2) {
                            if (count != cycler) {
                                playCount(urlMusic, cycler, 1);
                            } else {
                                isPlay = true;
                                if(position==bean.getData().size()){
                                    time1Question.start();
                                }else{
                                    timeQuestion.start();
                                }
                            }

                        } else if (cycler == 3) {
                            if (cycler - count == 2) {//波了一遍了
                                playCount(urlMusic, cycler, 1);
                            } else if (cycler - count == 1) {
                                playCount(urlMusic, cycler, 2);
                            } else {
                                isPlay = true;
                                if(position==bean.getData().size()){
                                    time1Question.start();
                                }else{
                                    timeQuestion.start();
                                }

                            }

                        } else if (cycler == 4) {


                        } else if (cycler == 5) {

                        }
                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始

                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误
                        break;
                }

            }
        });
        player.playUrl(Constant.IMAGE_HEAD + urlMusic);
    }

    //第一遍 第二遍
    private int rediaCount(int index) {
        int redia = 0;
        switch (index) {
            case 0:
                redia = R.raw.to1;
                break;
            case 1:
                redia = R.raw.to2;
                break;
        }
        return redia;
    }


    //播放本地12345
    private int redia(int index) {
        int redia = 0;

        switch (index) {
            case 0:
                redia = R.raw.redia1;
                break;
            case 1:
                redia = R.raw.redia2;
                break;
            case 2:
                redia = R.raw.redia3;
                break;
            case 3:
                redia = R.raw.redia4;
                break;
            case 4:
                redia = R.raw.redia5;
                break;
            case 5:
                redia = R.raw.redia6;
                break;
            case 6:
                redia = R.raw.redia7;
                break;
            case 7:
                redia = R.raw.redia8;
                break;
            case 8:
                redia = R.raw.redia9;
                break;
            case 9:
                redia = R.raw.redia10;
                break;
            case 10:
                redia = R.raw.redia11;
                break;
            case 11:
                redia = R.raw.redia12;
                break;
            case 12:
                redia = R.raw.redia13;
                break;
            case 13:
                redia = R.raw.redia14;
                break;
            case 14:
                redia = R.raw.redia15;
                break;
            case 15:
                redia = R.raw.redia16;
                break;
            case 16:
                redia = R.raw.redia17;
                break;
            case 17:
                redia = R.raw.redia18;
                break;
            case 18:
                redia = R.raw.redia19;
                break;
            case 19:
                redia = R.raw.redia20;
                break;
            case 20:
                redia = R.raw.redia21;
                break;
            case 21:
                redia = R.raw.redia22;
                break;
            case 22:
                redia = R.raw.redia23;
                break;
            case 23:
                redia = R.raw.redia24;
                break;
            case 24:
                redia = R.raw.redia25;
                break;
            case 25:
                redia = R.raw.redia26;
                break;
            case 26:
                redia = R.raw.redia27;
                break;
            case 27:
                redia = R.raw.redia28;
                break;
            case 28:
                redia = R.raw.redia29;
                break;
            case 29:
                redia = R.raw.redia30;
                break;
            case 30:
                redia = R.raw.redia31;
                break;
            case 31:
                redia = R.raw.redia32;
                break;
            case 32:
                redia = R.raw.redia33;
                break;
            case 33:
                redia = R.raw.redia34;
                break;
            case 34:
                redia = R.raw.redia35;
                break;
            case 35:
                redia = R.raw.redia36;
                break;
            case 36:
                redia = R.raw.redia37;
                break;
            case 37:
                redia = R.raw.redia38;
                break;
            case 38:
                redia = R.raw.redia39;
                break;
            case 39:
                redia = R.raw.redia40;
                break;
            case 40:
                redia = R.raw.redia41;
                break;
            case 41:
                redia = R.raw.redia42;
                break;
            case 42:
                redia = R.raw.redia43;
                break;
            case 43:
                redia = R.raw.redia44;
                break;
            case 44:
                redia = R.raw.redia45;
                break;
        }
        return redia;
    }

    //录音
    @SuppressLint("HandlerLeak")
    private void startRecord() {
        filePath = FileUtils.getAppPath();
        File file = new File(filePath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Toast.makeText(getContext(), "创建文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        filePath = FileUtils.getAppPath() + UUID.randomUUID().toString() + ".mp3";
        mRecorder = new MP3Recorder(new File(filePath));

        mRecorder.setErrorHandler(new Handler() {
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    Toast.makeText(getContext(), "没有麦克风权限", Toast.LENGTH_SHORT).show();
                    resolveError();
                }
            }
        });

        try {
            mRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "录音出现异常", Toast.LENGTH_SHORT).show();
            resolveError();
            return;
        }
    }

    /**
     * 录音异常
     */
    private void resolveError() {
        FileUtils.deleteFile(filePath);
        filePath = "";
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stop();
        }
    }

    //停止录音
    private void stopRecord() {
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.setPause(false);
            mRecorder.stop();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlay();
        stopRecord();
        YunQuestionSingle.getInstance().clearList();
    }

    //停止播放
    private void stopPlay() {
        //停止播放
        if (player != null) {
            player.stop();
            player = null;
        }
        if (audioText != null) {
            audioText.stop();
            audioText = null;
        }

        if (media1 != null) {
            media1.stop();
            media1 = null;
        }

        if (media2 != null) {
            media2.stop();
            media2 = null;
        }

        if (audioPlayer != null) {
            audioPlayer.stop();
            audioPlayer = null;
        }
    }

    //上传七牛
    private void uploadAvatar() {
        final QiniuYunUtil qiniuUploadMoreUtil = new QiniuYunUtil();
        qiniuUploadMoreUtil.upLoadFileToQiNiu(this, 0, 1, filePath);
        qiniuUploadMoreUtil.setQiniuUtilI(new QiniuYunUtil.QiniuUtilI() {
            @Override
            public void succeed(boolean allok, int current, String qiNiuBackPicPath) {
                if (allok) {
                    qnPath = qiNiuBackPicPath;
                    isqnPath = true;

                    if(isAudio){
                        //保存错题
                        YunQuestionBean dataBean = new YunQuestionBean();
                        dataBean.setId(bean.getData().get(position-1).getId());
                        dataBean.setAnswer(qnPath);
                        dataBean.setResult(true);
                        YunQuestionSingle.getInstance().addWorks(dataBean);

                        String question_answers = JsonParseUtil.ListToStr(YunQuestionSingle.getInstance().getWorksList());
                        int score = 0;
                        for(int i=0;i<YunQuestionSingle.getInstance().getWorksList().size();i++){
                            if(YunQuestionSingle.getInstance().getWorksList().get(i).isResult()){
                                score+=4;
                            }
                        }
                        yunSubmitPresenter.submit(question_answers,score+"",bean.getExam_id()+"","");
                    }
                }
            }

            //七牛上传失败
            @Override
            public void failure() {
                qnPath = "";
                isqnPath = true;
            }

            //七牛上传中
            @Override
            public void progress(int current, int progress) {
                isqnPath = false;
            }
        });
    }


    //每道小题的倒计时
    class Time extends CountDownTimer {

        Time(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {
            tvTime.setText("倒计时：" + millisUntilFinished / 1000 + "s");
            progress1.setProgress(progress((int) (millisUntilFinished / 1000)));
        }

        @Override
        public void onFinish() {
            stopPlay();
            //倒计时结束
            timeQuestion.cancel();
            tvTime.setText("倒计时：20s");
            //保存错题
            YunQuestionBean dataBean = new YunQuestionBean();
            dataBean.setId(bean.getData().get(position).getId());
            dataBean.setAnswer("0");
            dataBean.setResult(false);
            YunQuestionSingle.getInstance().addWorks(dataBean);

            next();
        }
    }

    //每道小题的倒计时
    class Time1 extends CountDownTimer {

        Time1(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {
            tvTime.setText("倒计时：" + millisUntilFinished / 1000 + "s");
            progress1.setProgress(progress((int) (millisUntilFinished / 1000)));
        }

        @Override
        public void onFinish() {
            stopPlay();
            //倒计时结束
            time1Question.cancel();

            if(isAudio){
                stopRecord();
                tvRadio.setText("录音结束");
                tvRadio.setEnabled(false);
                llLuYin.setVisibility(View.GONE);
                uploadAvatar();
                isAudio = false;
            }else{
                //保存错题
                YunQuestionBean dataBean = new YunQuestionBean();
                dataBean.setId(bean.getData().get(position-1).getId());
                dataBean.setAnswer("");
                dataBean.setResult(false);
                YunQuestionSingle.getInstance().addWorks(dataBean);

                String question_answers = JsonParseUtil.ListToStr(YunQuestionSingle.getInstance().getWorksList());
                int score = 0;
                for(int i=0;i<YunQuestionSingle.getInstance().getWorksList().size();i++){
                    if(YunQuestionSingle.getInstance().getWorksList().get(i).isResult()){
                        score+=4;
                    }
                }
                yunSubmitPresenter.submit(question_answers,score+"",bean.getExam_id()+"","");
            }
        }
    }

    private int progress(int a) {
        return 100 - ((a - 1) * 5);
    }

    @Override
    public void showYunSubmit() {
        showFinishResult();
    }

    //答题结束 弹窗
    private void showFinishResult(){
        final YunOutPopup yunOutPopup = new YunOutPopup(YunExaminationTwoActivity.this);
        yunOutPopup.setPopupWindowFullScreen(true);
        yunOutPopup.setDismissWhenTouchOutside(false);

        yunOutPopup.showPopupWindow();
        yunOutPopup.setModeListener(new YunOutPopup.IModeSelection() {
            @Override
            public void getMode(int mode) {
                if (mode == 1) {//确定
                    yunOutPopup.dismiss();
                    setResult(1024);
                    YunExaminationTwoActivity.this.finish();
                }
            }
        });
    }

}
